package com.dbapp.garden.controller.sys;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.dbapp.garden.config.security.PermissionUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.SysRole;
import com.dbapp.garden.entity.SysRoleUser;
import com.dbapp.garden.entity.SysUser;
import com.dbapp.garden.service.SysRoleService;
import com.dbapp.garden.service.SysRoleUserService;
import com.dbapp.garden.service.SysUserService;
import com.dbapp.garden.vm.SysUserEditVm;
import com.dbapp.garden.vm.SysUserVm;

@Controller
public class SysUserController {

	@Autowired
	private SysUserService userService;
	@Autowired
	private SysRoleService roleService;
	
	@Autowired
	private SysRoleUserService roleUserService;

	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;

	@GetMapping("/user")
	@PreAuthorize("hasAuthority('PERMISSION_USER')")
	public String toUserListPage(HttpServletRequest request) {
		return "user/userlist";

	}

	@PostMapping("/userlist")
	@ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_USER')")
	public Map<String, ?> userList(String param,@SessionAttribute("user") PermissionUser user) {

		Map<String, Object> paramMap = DataTableUtils.parseParam(param);
		if (paramMap == null) {
			return RenderJSON.makeMap(-1, "参数不合法！", null, "");
		}
		String sEcho = (String) paramMap.get("sEcho");
		String sSearch = (String) paramMap.get("sSearch");
		int iDisplayStart = (int) paramMap.get("iDisplayStart");
		int iDisplayLength = (int) paramMap.get("iDisplayLength");

		paramMap.clear();
		paramMap.put("search", sSearch);
		paramMap.put("start", iDisplayStart);
		paramMap.put("limit", iDisplayLength);
		paramMap.put("gardenId",user.getGardenId());

		List<SysUser> userList = userService.getUserList(paramMap);
		Integer count = userService.getUserCount(paramMap);

		return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, userList, "");
	}

	@GetMapping("/useradd")
	@PreAuthorize("hasAuthority('PERMISSION_USER_ADD')")
	public String toUserAddPage(HttpServletRequest request, Model model) {

		Map<String, Object> paramMap = new HashMap<>();
		List<SysRole> roles = roleService.getRoleList(paramMap);
		model.addAttribute("roles", roles);
		return "user/useradd";

	}
	@GetMapping("/useredit/{id}")
	@PreAuthorize("hasAuthority('PERMISSION_USER_EDIT')")
	public String toUserEditPage(HttpServletRequest request,@PathVariable("id") Integer id, Model model) {
		
		Map<String, Object> paramMap = new HashMap<>();
		List<SysRole> roles = roleService.getRoleList(paramMap);
		SysUser user=userService.findUserById(id);
		SysRoleUser roleuser=roleUserService.findByUserId(id);
		model.addAttribute("roles", roles);
		model.addAttribute("user", user);
		model.addAttribute("roleuser", roleuser);
		return "user/useredit";
		
	}

	@PostMapping("/useradd")
	@ResponseBody
	@Transactional(rollbackFor=Exception.class)
	@PreAuthorize("hasAuthority('PERMISSION_USER_ADD')")
	public Map<String, ?> addUser(HttpServletRequest request, @RequestBody @Valid SysUserVm userVm) {
		SysUser user = new SysUser();
		user.setUserName(userVm.getUserName());
		user.setUserPhone(userVm.getUserPhone());
		user.setUserRealName(userVm.getUserRealName());
		String password = userVm.getUserPassword();
		user.setUserPassword(bCryptPasswordEncoder.encode(password));
		user.setUpdateTime(new Date());
		user.setUserRegisterTime(new Date());
		
		Integer result = userService.saveUser(user);
		SysRoleUser roleUser=new SysRoleUser();
		roleUser.setRoleId(userVm.getUserRole());
		roleUser.setUserId(user.getId());
		roleUser.setCreateTime(new Date());
		roleUser.setUpdateTime(new Date());
		roleUserService.save(roleUser);
		if (result != null && result > 0) {
			return RenderJSON.makeStandMap(1, "恭喜您，添加成功！", "ok");
		} else {
			return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
		}

	}
	@PostMapping("/useredit/{id}")
	@ResponseBody
	@Transactional(rollbackFor=Exception.class)
	@PreAuthorize("hasAuthority('PERMISSION_USER_EDIT')")
	public Map<String, ?> editUser(HttpServletRequest request,@PathVariable("id") Integer id,  @RequestBody @Valid SysUserEditVm userVm) {
		SysUser user =userService.findUserById(id);
		if(user==null){
			return RenderJSON.makeStandMap(1, "对不起，用户不存在，编辑失败！", "error");
		}
		user.setUserPhone(userVm.getUserPhone());
		user.setUserRealName(userVm.getUserRealName());
		user.setUpdateTime(new Date());
		
		Integer result = userService.saveUser(user);
		SysRoleUser roleUser=roleUserService.findByUserId(id);
		roleUser.setRoleId(userVm.getUserRole());
		roleUser.setUserId(user.getId());
		roleUser.setUpdateTime(new Date());
		roleUserService.save(roleUser);
		if (result != null && result > 0) {
			return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
		} else {
			return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
		}
		
	}
	@DeleteMapping("/userdelete/{id}")
	@ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_USER_DELETE')")
	public Map<String, ?> addUser(HttpServletRequest request, @PathVariable("id") Integer id) {
		Integer result=userService.delete(id);
		
		if(result!=null&&result>0){
			return RenderJSON.makeStandMap(1, "恭喜您，删除成功！", "ok");
		}else{
			return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
		}
		
	}
	@GetMapping("/access-denied")
	public String accessDeniedPage(HttpServletRequest request) {
		return "user/403";

	}

	@GetMapping("/usernamecheck")
	@ResponseBody
	public boolean checkRoleNameExit(String userName) {
		SysUser role = userService.findUserByUserName(userName);
		return role == null ? true : false;
	}
}
